/* 
 * [New BSD License (BSD 3-Clause License)]
 * Copyright (c) 2012, Max Bechtold
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     - Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     - Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     - Neither the name of the Rel2Xml Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package maxbe.rel2xml.generator.dml;

import java.util.ArrayList;
import java.util.List;

import maxbe.rel2xml.generator.Table;
import maxbe.rel2xml.util.Config;

/**
 * Enhanced wrapper class representing base tables or subqueries in a query.
 * Entities can be connected through the children field. The translation of
 * queries includes an attempt to connect all entities to form a tree to enable
 * hierarchical output of joined subtrees. That tree will eventually be
 * translated into a FLOWR expression. If no tree can be formed, a flat join
 * will be performed.
 * 
 * @author Max Bechtold
 * 
 */
public class Entity {

	/** If not null, this entity is a base table */
	private final Table table;

	/**
	 * If not null, this entity is the result of a subquery -> not supported atm
	 */
	private final Query subQuery;

	/** The alias of this entity */
	private String alias;

	/**
	 * Lists all entities that can be mapped as children in the result (if
	 * hierarchical joins are performed)
	 */
	private final List<Entity> children;

	/** The entity under which this entity is mapped as a child */
	private Entity parent;

	/** The column that is referenced for the join */
	private ResultColumn refJoinColumn;

	/**
	 * If true, this entity's table is mapped in the result either not under its
	 * parent, or under its parent but not via the foreign key that defines the
	 * mapping
	 */
	private boolean remapped = false;

	public Entity(String alias, Table table) {
		this.alias = alias;
		this.table = table;
		children = new ArrayList<Entity>();
		subQuery = null;
	}

	public Entity(String alias, Query subQuery) {
		this.alias = alias;
		this.subQuery = subQuery;
		children = new ArrayList<Entity>();
		table = null;
	}

	public boolean isTable() {
		return table != null;
	}

	public boolean isRemapped() {
		return remapped;
	}

	public Table getTable() {
		return table;
	}

	public Query getSubQuery() {
		return subQuery;
	}

	public String getAlias() {
		return alias;
	}

	public List<Entity> getChildren() {
		return children;
	}

	public Entity getParent() {
		return parent;
	}

	public ResultColumn getRefJoinColumn() {
		return refJoinColumn;
	}

	public boolean isAncestorOf(Entity entity) {
		if (children.contains(entity))
			return true;
		else
			for (Entity e : children)
				if (e.isAncestorOf(entity))
					return true;
		return false;
	}

	public void setParent(Entity parent) {
		this.parent = parent;
		if (parent != null)
			parent.addChild(this);
	}

	public void setAlias(String alias) {
		this.alias = alias;
	}

	public void setRemapped(boolean remapped) {
		this.remapped = remapped;
	}

	public void addChild(Entity child) {
		child.parent = this;
		this.children.add(child);
	}

	public void setRefJoinColumn(ResultColumn refJoinColumn) {
		this.refJoinColumn = refJoinColumn;
	}

	public String toSql() {
		if (isTable()) {
			return table.getName();
		} else {
			return "(" + subQuery.toSQL() + ")";
		}
	}

	public String getXPathSelector() {
		String result = "";
		if (refJoinColumn != null)
			if (!remapped)
				result += '$' + refJoinColumn.getEntity().alias
						+ table.getXPathSelector(true);
			else
				result += String.format("fn:idref($%s/%s)/..",
						refJoinColumn.getEntity().alias,
						refJoinColumn.getXmlName());
		else
			result += "$" + Config.ROOT_NODE_VAR + table.getXPathSelector();
		return result;
	}

	@Override
	public String toString() {
		return toSql();
	}
}
